package config

import (
	"encoding/json"
	"errors"
	"flag"
	"log"
	"os"
)

type DatabaseConfig struct {
	Source string `json:"source"`
}

type config struct {
	Database DatabaseConfig `json:"database"`
	Port     int            `json:"port"`
}

var ErrConfigLoad = errors.New("load config error")

var Config = config{}

func LoadConfig() {
	configFile := flag.String("conf", "conf.json", "config path. If not exist, will use command-line arguments")
	flag.StringVar(&Config.Database.Source, "database", "root:root@tcp(127.0.0.1:3306)/code", "mysql connection source")
	flag.IntVar(&Config.Port, "port", 28375, "the port to expose")
	flag.Parse()

	file, err := os.Open(*configFile)

	if os.IsNotExist(err) {
		return
	}
	if err != nil {
		log.Panic(ErrConfigLoad, err)
	}
	defer file.Close()
	decoder := json.NewDecoder(file)

	if err = decoder.Decode(&Config); err != nil {
		log.Panic(ErrConfigLoad, err)
	}
}
